package com.yeskery.nut.application;

import javax.net.ssl.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyStore;

/**
 * 默认基于 <b>jks</b> 格式证书的 {@link SecureServerContext} 实现
 * @author sprout
 * 2022-05-19 14:26
 */
public class JksSecureServerContext implements SecureServerContext {

    /** jks证书库路径 */
    private final String jksPath;

    /** jks证书库密码 */
    private final String jksPassword;

    /**
     * 创建一个基于 <b>jks</b> 格式证书的 {@link SecureServerContext} 实现
     * @param jksPath jks证书库路径
     * @param jksPassword jks证书库密码
     */
    public JksSecureServerContext(String jksPath, String jksPassword) {
        this.jksPath = jksPath;
        this.jksPassword = jksPassword;
    }

    @Override
    public SSLContext getSslContext(String algorithm) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(Files.newInputStream(Paths.get(jksPath)), jksPassword.toCharArray());

        //创建密钥管理器
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(keyStore, jksPassword.toCharArray());
        KeyManager[] km = keyManagerFactory.getKeyManagers();

        // 创建信任库
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        trustManagerFactory.init(keyStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();

        //初始化 SSLContext TLSv1 SSLv3
        SSLContext sslContext = SSLContext.getInstance(algorithm);
        sslContext.init(km, tm, null);
        return sslContext;
    }

    /**
     * 获取jks证书库路径
     * @return jks证书库路径
     */
    public String getJksPath() {
        return jksPath;
    }

    /**
     * 获取jks证书库密码
     * @return jks证书库密码
     */
    public String getJksPassword() {
        return jksPassword;
    }
}
